<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use DateTime;
use fast\Http;
use fast\Random;
use fast\Snowflake;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;
use think\Validate;
use WeChatPay\Crypto\AesGcm;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Formatter;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Log;
use Yansongda\Pay\Pay;
use function fast\e;

/**
 * 订单接口
 */
class Epay extends Api
{
    protected $noNeedLogin = ['notifyx'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 微信支付(公众号支付&PC扫码支付)
     */
    public function wechat()
    {
        //$config = Service::getConfig('wechat');


        $this->error("暂未开通");

        $order_no = $this->request->post("order_no");
        if (empty($order_no)) {
            $this->error("订单号不能为空");
        }

        $substring = mb_substr($order_no, 0, 1);
        //订单
        if ($substring == "D") {
            $order = Db::name("order")->where("order_no",$order_no)->find();

        } elseif ($substring == "U") {
            $order = Db::name("order_vip")->where("order_no",$order_no)->find();

        }  elseif ($substring == "C") {
            $order = Db::name("course_order")->where("order_no",$order_no)->find();

        } else {
            $order = Db::name("order")->where("order_no",$order_no)->find();

        }

        //超时订单无法支付
        if ($substring == "U") {
            $time = time();
            if ($order["createtime"] <= ($time-300)) {
                $this->error("订单超时，无法支付", "");
            }

        }


        if (empty($order)) {
            $this->error("订单不存在");
        }

        if ($order["pay_status"] == 1) {
            $this->error("无需重复支付");
        }

        $user = Db::name("user")->where("id",$order["user_id"])->find();
        if (empty($user)) {
            $this->error("用户不存在");
        }

        $resp = (new \wxpay\Pay)->pay(intval($order["price"] * 100),$order_no,$user["openid"],"支付");

        if (!$resp) {
            $this->error("支付失败，请稍后再试", "");
        }

        $this->success("",$resp);




    }

    /**
     * 支付成功回调
     */
    public function notifyx()
    {
        $resp = (new \wxpay\Pay)->notify();
        if (!empty($resp)) {
            $order_no = $resp["out_trade_no"];
            Log::info("支付回调单号：".$order_no);
            if (!empty($order_no)) {
                $substring = mb_substr($order_no, 0, 1);

                //订单
                if ($substring == "D") {
                    $order = Db::name("order")->where("order_no",$order_no)->find();
                    if ($order["pay_status"] == 1){
                        echo '{"code": "SUCCESS", "message": ""}';
                        return;
                    }

                    $res = $this->addBill($order["user_id"],$order["price"],$order_no,1,2);

                    if ($res) {
                        $order = Db::name("order")->where("order_no",$order_no)->update([
                            "pay_status"=>1,
                            "pay_time"=>time(),
                            "status"=>1,
                        ]);
                        $car_old = Db::name("car_old")->where("id",$order["car_old_id"])->update([
                            "trade_status"=>3,
                        ]);

                        echo '{"code": "SUCCESS", "message": ""}';
                    }


                    return;
                }

                //会员充值
                if ($substring == "U") {

                    $order_vip = Db::name("order_vip")->where("order_no",$order_no)->find();
                    if ($order_vip["pay_status"] == 1) {
                        echo '{"code": "SUCCESS", "message": ""}';
                        return;
                    }

                    Db::name("order_vip")->where("order_no",$order_no)->update([
                        "pay_status"=>1,
                        "pay_time"=>time(),
                    ]);
                    $user = Db::name("user")->where("id",$order_vip["user_id"])->find();
                    if ($user["vip_status"] == 0) {
                        // 字符串日期
                        $dateString = date("Y-m-d H:i:s");
                    } else {

                        // 检查$datetime是否大于$now
                        if ($user["vip_exp_time"] > date("Y-m-d H:i:s")) {
                            $dateString = $user["vip_exp_time"];
                           // echo "给定时间大于或等于当前时间";
                        } else {
                            //echo "给定时间小于当前时间";
                            $dateString = date("Y-m-d H:i:s");
                        }

                    }
                    $vip_time = $order_vip["vip_time"];
                    $nextMonth = strtotime($dateString . " +$vip_time month");
                    Db::name("user")->where("id",$order_vip["user_id"])->update([
                        "vip_status"=>1,
                        "vip_exp_time"=>date('Y-m-d H:i:s', $nextMonth),
                    ]);


                    $data["order_no"] = $order_no;
                    $data["user_id"] = $order_vip["user_id"];
                    $data["money"] = $order_vip["price"];

                    $data["before"] = $user["money"];
                    $data["after"] = $user["money"];

                    $data["type"] = 2;
                    $data["source"] = 1;
                    $data["createtime"] = time();
                    Db::name("user_bill")->insert($data);


                    echo '{"code": "SUCCESS", "message": ""}';
                    return;

                }


                //课程
                if ($substring == "C") {
                    $order = Db::name("course_order")->where("order_no",$order_no)->find();
                    if ($order["pay_status"] == 1){
                        echo '{"code": "SUCCESS", "message": ""}';
                        return;
                    }


                    $order = Db::name("order")->where("order_no",$order_no)->update([
                        "pay_status"=>1,
                        "pay_time"=>time()
                    ]);

                    $data["order_no"] = $order_no;
                    $data["user_id"] = $order["user_id"];
                    $data["money"] = $order["price"];

                    $data["before"] = $order["money"];
                    $data["after"] = $order["money"];

                    $data["type"] = 2;
                    $data["source"] = 4;
                    $data["createtime"] = time();
                    Db::name("user_bill")->insert($data);

                    echo '{"code": "SUCCESS", "message": ""}';
                    return;
                }



            }

        }
    }

    //创建账单
    public function addBill($user_id,$money,$order_no,$type,$source) {
        $user = Db::name("user")->where("id",$user_id)->find();
        if ($type == 1) {
            $res = Db::name("user")->where("id",$user_id)->inc("margin",$money)->update();
        } else {
            $res = Db::name("user")->where("id",$user_id)->inc("money",$money)->update();
        }
        if ($res) {
            $data["order_no"] = $order_no;
            $data["user_id"] = $user_id;
            $data["money"] = $money;
            if ($type == 1) {
                $data["before"] = $user["margin"];
                $data["after"] = $user["margin"]+$money;
            } else {
                $data["before"] = $user["money"];
                $data["after"] = $user["money"]+$money;
            }

            $data["type"] = $type;
            $data["source"] = $source;
            $data["createtime"] = time();
            Db::name("user_bill")->insert($data);
            return true;
        }

        return false;

    }

}


